package com.chaodev.base.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.model.UserInfo;

import java.io.UnsupportedEncodingException;
import java.util.*;

//@Component
public class JwtUtil {

    //密钥
    public static final String SECRET = "sdjhakdhajdklsl;o653632";
    //过期时间:秒
    public static final int EXPIRE = 30*60;
//    @Autowired
//    public  RedisDao redisDao;

    public static String createToken(String userId,String userName,String depart_id,String role_id,String roleName,String departName,String accNumber,String areaCode,String acctSetId,String accSetName,String mofDivCode,String fiscalYear,String UserSkin) throws Exception {

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.SECOND, EXPIRE);
        Date expireDate = nowTime.getTime();

        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create()
                .withHeader(map)//头
                .withClaim("userId", userId)
                .withClaim("userName", userName)
                .withClaim("depart_id", depart_id)
                .withClaim("role_id", role_id)
                .withClaim("roleName", roleName)
                .withClaim("departName", departName)
                .withClaim("accNumber", accNumber)
                .withClaim("areaCode", areaCode)
                .withClaim("acctSetId", acctSetId)
                .withClaim("accSetName", accSetName)
                .withClaim("mofDivCode", mofDivCode)
                .withClaim("fiscalYear", fiscalYear)
                .withClaim("userSkin", UserSkin)
                //.withSubject("测试")//
                .withIssuedAt(new Date())//签名时间
                .withExpiresAt(expireDate)//过期时间
                .sign(Algorithm.HMAC256(SECRET));//签名
        return token;
    }

    public static Map<String, Claim> verifyToken(String token)throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        }catch (Exception e){
            throw new RuntimeException("凭证已过期，请重新登录");
        }
        return jwt.getClaims();
    }

    public static UserInfo getUserInfoFromToken(String token, RedisDao redisDao){
        UserInfo userInfo=new UserInfo();
//        userInfo=(UserInfo) redisDao.vGet(token);
        String userInfoStr=(String) redisDao.vGet(token);
        userInfo=JSONObject.parseObject(userInfoStr,UserInfo.class);
        UserInfo userInfonew=new UserInfo();
//        DecodedJWT decodedJWT= JWT.decode(token);
//        String str=decodedJWT.getPayload();
//        byte[] orignB=Base64.getUrlDecoder().decode(str);
//        String orgin=new String(orignB);
//        JSONObject jsonObject= JSON.parseObject(orgin);
        userInfonew.setUserId(userInfo.getUserId());
//        String departid=jsonObject.get("depart_id").toString();
        userInfonew.setDepartId(userInfo.getDepartId());
        userInfonew.setRoleId(userInfo.getRoleId());
        userInfonew.setUserName(userInfo.getUserName());
        userInfonew.setDepartName(userInfo.getDepartName());
        userInfonew.setRoleName(userInfo.getRoleName());
        userInfonew.setRealAccNbr(userInfo.getRealAccNbr());
        userInfonew.setAreaCode(userInfo.getAreaCode());

        userInfonew.setZhUserId(userInfo.getZhUserId());
        userInfonew.setKjUserId(userInfo.getKjUserId());

        userInfonew.setRealUserId(userInfo.getRealUserId());

//        userInfonew.setACCT_SET_ID(jsonObject.getString("acctSetId"));
//        userInfonew.setACCT_SET_NAME(jsonObject.getString("accSetName"));
//        userInfonew.setMOF_DIV_CODE(jsonObject.getString("mofDivCode"));
////        userInfonew.setFISCAL_YEAR(jsonObject.getString("fiscalYear"));
        return userInfonew;
    }

    public static String getSECRET() {
        return SECRET;
    }

    public static int getEXPIRE() {
        return EXPIRE;
    }

    /*
     * Token 是否过期验证
     */
    public boolean isTokenExpired (Date expirationTime) {
        return expirationTime.before(new Date());
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NOdW1iZXIiOiIxODk4Nzg3MTUwMCIsInJvbGVfaWQiOiIxMDExIiwiZGVwYXJ0X2lkIjoiMTAwMCIsInJvbGVOYW1lIjoi5rWL6K-VIiwidXNlck5hbWUiOiLnrqHnkIblkZgiLCJleHAiOjE1Nzc2NzQ2OTAsInVzZXJJZCI6ImFkbWluIiwiaWF0IjoxNTc3NjcyODkwLCJkZXBhcnROYW1lIjoi5LqR5Y2X55yB5pys57qnIn0.o6_xm2UT_Xy--dTHkuN4M0E18nTH1nHzH1O4ZJ1bD44";
       String token1="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NOdW1iZXIiOiIxODk4Nzg3MTUwMCIsInJvbGVfaWQiOiIxMDAwIiwiZGVwYXJ0X2lkIjoiMTAwMCIsInJvbGVOYW1lIjoi566h55CG5ZGYIiwidXNlck5hbWUiOiLnrqHnkIblkZgiLCJleHAiOjE1Nzc2NzUxOTIsInVzZXJJZCI6ImFkbWluIiwiaWF0IjoxNTc3NjczMzkyLCJkZXBhcnROYW1lIjoi5LqR5Y2X55yB5pys57qnIn0.RncViE4vJ4i216xR6elsSErsWuoz7ah0E38iSzxClKo";
        String token2="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NOdW1iZXIiOiIxODk4Nzg3MTUwMCIsInJvbGVfaWQiOiIxMDExIiwiZGVwYXJ0X2lkIjoiMTAwMCIsInJvbGVOYW1lIjoi5rWL6K-VIiwidXNlck5hbWUiOiLnrqHnkIblkZgiLCJleHAiOjE1Nzc2Nzc2ODAsInVzZXJJZCI6ImFkbWluIiwiaWF0IjoxNTc3Njc1ODgwLCJkZXBhcnROYW1lIjoi5LqR5Y2X55yB5pys57qnIn0.sIo8enivRTHhcQeDH8HLaXZ0dYu704GA-6tzEqAgUQQ";
        String token3="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NOdW1iZXIiOiIxODEwODcxOTk5NCIsInJvbGVfaWQiOiIxMDAwIiwiZGVwYXJ0X2lkIjoiMTAwMCIsInJvbGVOYW1lIjoi566h55CG5ZGYIiwidXNlck5hbWUiOiJ4eTEiLCJleHAiOjE1Nzc2ODY4NjAsInVzZXJJZCI6Inh5IiwiaWF0IjoxNTc3Njg1MDYwLCJkZXBhcnROYW1lIjoi5LqR5Y2X55yB5pys57qnIn0.RdMLJ7453FI1bWj-X8Dkth_39xHf970-Bm7bJF-dmMU";

        String token4="";
        try{
            token4=createToken( "admin","管理员","1000","1011","工单发起人","云南省本级","18987871500","5300","","","","","");

       }catch (Exception e){
           e.printStackTrace();
       }
        UserInfo userInfo=new UserInfo();
        DecodedJWT decodedJWT= JWT.decode(token4);
        String str=decodedJWT.getPayload();
        byte[] orignB=Base64.getUrlDecoder().decode(str);
        String orgin=new String(orignB);
        JSONObject jsonObject= JSON.parseObject(orgin);
        userInfo.setUserId(jsonObject.get("userId").toString());
        String departid=jsonObject.get("depart_id").toString();
        userInfo.setDepartId(departid);
        userInfo.setRoleId(jsonObject.getString("role_id"));
        userInfo.setUserName(jsonObject.getString("userName"));
        userInfo.setDepartName(jsonObject.getString("departName"));
        userInfo.setRoleName(jsonObject.getString("roleName"));
        userInfo.setRealAccNbr(jsonObject.getString("accNumber"));
        System.out.println(userInfo.toString());

    }

    public static DecodedJWT TokenStrToJwt(String token) throws Exception
    {
//        JWTVerifier verifier = JWT.require(Algorithm.HMAC512(SECRET)).build();
////        DecodedJWT jwt = null;
////        jwt = verifier.verify(token);
////        return jwt;

        DecodedJWT decodedJWT= JWT.decode(token);
        return decodedJWT;

    }


}
